﻿using System;
using System.Data;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.IO;

namespace ITViet.Web.App_Code
{
    public class SendMail
    {
        public static string SUCCESS = "SUCCESS";
        public static string ERROR = "ERROR";

        public static string StartSendMail(MailMessage message)
        {
            string host = GlobalCache.Instance.SMTPHost;
            int port = GlobalCache.Instance.SMTPPort;
            string user = GlobalCache.Instance.SMTPUser;
            string pass = GlobalCache.Instance.SMTPPass;
            bool ssl = GlobalCache.Instance.SMTPSSL;
            message.From = new MailAddress(user);
            SmtpClient mailClient = new SmtpClient(host, port);
            mailClient.Timeout = GlobalCache.Instance.MailTimeOut;
            mailClient.Credentials = new NetworkCredential(user, pass);
            mailClient.EnableSsl = ssl;
            try
            {
                mailClient.Send(message);
            }
            catch (Exception ex)
            {
                return ERROR + "|" + ex.Message;
            }
            return SUCCESS;
        }

        public static MailMessage PrepareMailMessage(string[] toAddress, string[] ccAddress, string[] bccAddress,
                                  string subject, string content, string[] attachment)
        {
            MailMessage message = new MailMessage();

            if (toAddress != null)
                foreach (string email in toAddress)
                    message.To.Add(new MailAddress(email));

            if (ccAddress != null)
                foreach (string email in ccAddress)
                    message.CC.Add(new MailAddress(email));

            if (bccAddress != null)
                foreach (string email in bccAddress)
                    message.Bcc.Add(new MailAddress(email));

            if (attachment != null)
                foreach (string file in attachment)
                {
                    string contentID = Path.GetFileName(file).Replace(".", "") + "@zofm";
                    Attachment attachedFile = new Attachment(file);
                    attachedFile.ContentDisposition.Inline = true;
                    attachedFile.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                    attachedFile.ContentId = contentID;
                    //attachedFile.ContentType.MediaType = Utils.GetMimeType(file);
                    attachedFile.ContentType.Name = Path.GetFileName(file);
                    attachedFile.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
                    message.Attachments.Add(new Attachment(file));
                }
            message.Priority = MailPriority.High;
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = content;

            return message;
        }
    }
}
